package com.itheima.tlias84.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias84.Po.InsertClazzParam;
import com.itheima.tlias84.Po.SelectClazzPageParam;
import com.itheima.tlias84.Po.UpdateClazzParam;
import com.itheima.tlias84.Service.ClazzService;
import com.itheima.tlias84.Util.ResultUtil;
import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.dto.SelectClazzDTO;
import com.itheima.tlias84.entity.Clazz;
import com.itheima.tlias84.mapper.ClazzMapper;
import com.itheima.tlias84.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class ClazzServiceImpl implements ClazzService {
@Autowired
ClazzMapper clazzMapper;

    @Override
    public List<SelectClazzDTO> selectAll() {
        List<SelectClazzDTO> selectClazzDTOS = clazzMapper.selectAll();
            return selectClazzDTOS;
    }

    @Override
    public SelectClazzDTO selectClazzById(Integer id) {
        SelectClazzDTO selectClazzDTO = clazzMapper.selectClazzById(id);
        return selectClazzDTO;
    }

  /**
 * 分页查询班级信息
 *
 * @param param 分页查询参数对象，包含页码和每页大小等信息
 * @return 返回分页查询的结果，包括总记录数和当前页的数据
 */
@Override
public ResultUtil selectClazzByPage(SelectClazzPageParam param) {
    // 启动分页，配置当前页码和每页大小
    Page<Object> page = PageHelper.startPage(param.getPage(), param.getPageSize());
    // 调用Mapper执行分页查询，获取班级数据
    List<SelectClazzDTO> dtos = clazzMapper.selectClazzByPage(param);
    // 创建PageVO对象用于封装分页数据
    PageVO<SelectClazzDTO> pageVO = new PageVO<>();
    // 设置总记录数
    pageVO.setTotal(page.getTotal());
    // 设置当前页的数据
    pageVO.setRows(dtos);
    // 返回成功结果，携带分页数据
    return ResultUtil.success(pageVO);
}


    @Log
    @Override
    public int insertClazz(InsertClazzParam param) {
        Clazz build = Clazz.builder()
                .name(param.getName())
                .room(param.getRoom())
                .beginDate(param.getBeginDate())
                .endDate(param.getEndDate())
                .masterId(param.getMasterId())
                .subject(param.getSubject())
                .updateTime(param.getUpdateTime())
                .createTime(param.getCreateTime())
                .build();
        return clazzMapper.insertClazz(build);

    }
    @Log
    @Override
    public int deleteById(Integer id) {
        return clazzMapper.deleteById(id);
    }

    @Log
    @Override
    public ResultUtil updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        Clazz selected = clazzMapper.selectClazzByName(clazz.getName());
        if(Objects.nonNull(selected)&& selected.getId()!=clazz.getId()){
            return ResultUtil.fail("该班级已存在");
        }
        clazzMapper.updateClazz(clazz);
        return ResultUtil.success("修改班级信息成功");
    }
}
